package com.jjyu.security;

import com.jjyu.entity.User;
import com.jjyu.service.UserService;
import com.jjyu.utils.JWTUtils;
import com.jjyu.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;


    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userService.findByUserName(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("User not found");
        }
        LoginUserDetails loginUserDetails = new LoginUserDetails(user);
        Map<String, Object> claims = Map.of("userId", user.getUserId(), "name", user.getName(), "email", user.getEmail());

        String token= JWTUtils.generateToken(claims);
        redisUtils.set("token:"+user.getUserId(), token,10000);
        System.out.println("token:"+token);
        Map<String, Object> stringObjectMap = JWTUtils.parseToken(token);
        System.out.println("stringObjectMap:"+stringObjectMap);
        Map<String, Object> stringObjectMapRedis = JWTUtils.parseToken(redisUtils.get("token:"+user.getUserId()).toString());
        System.out.println("stringObjectMapRedis:"+stringObjectMapRedis);


        return loginUserDetails;
    }
}
